﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;

namespace PlutoStudio
{
    public static class XmlExtensions
    {
        /// <summary>
        /// 将指定的Xml文档反序列化成指定类型的对象。
        /// </summary>
        /// <typeparam name="T">对象的类型</typeparam>
        /// <param name="xml">要反序列化的Xml文档</param>
        /// <returns>反序列化生成的对象</returns>
        public static T FromXml<T>(this string xml)
        {
            using (var stream = new StringReader(xml))
            {
                System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                return (T)xmlSerializer.Deserialize(stream);
            }
        }

        /// <summary>
        /// 将指定的对象序列化成Xml文档。
        /// </summary>
        /// <param name="value">要序列化的对象</param>
        /// <returns>生成的Xml文档</returns>
        public static string ToXml(this object value)
        {
            var result = new StringBuilder();
            using (var stream = XmlWriter.Create(result, new XmlWriterSettings { Encoding = Encoding.UTF8 }))
            {
                stream.WriteProcessingInstruction("xml", @"version=""1.0"" encoding=""utf-8""");
                System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(value.GetType());
                xml.Serialize(stream, value);
            }
            return result.ToString();
        }


    }
}
